import { Observable } from 'rxjs'
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'

@Injectable()
export class AuditInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
    const request = context.switchToHttp().getRequest<ExpressRequest>() // 获取请求上下文中的 request 对象
    const user: JwtPayload = Reflect.get(request, 'user')
    const method = request.method.toUpperCase()
    const contentType = request.headers['content-type']

    // 是否为上传请求
    const isUploadAction = contentType?.toLowerCase().includes('multipart/form-data')

    if (user && !isUploadAction) {
      // 对 POST 请求添加 createBy
      if (method === 'POST') {
        request.body.createBy = user.username
        request.body.updateBy = user.username
      }

      // 对 PUT/PATCH 请求添加 updateBy 和 updateTime
      if (method === 'PUT' || method === 'PATCH') {
        request.body.updateBy = user.username
      }
    }

    return next.handle()
  }
}
